/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jus.aor.mobilagent.loader;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.jar.JarException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jus.aor.mobilagent.kernel.Jar;

/**
 *
 * @author Rémi PIOTAIX <remi.piotaix@gmail.com>
 */
public class BAMLoader extends ClassLoader {

    private Map<String, byte[]> classData = new HashMap<>();

    public BAMLoader(ClassLoader parent) {
        super(parent);
    }
    
    public void addJar(Jar j){
        readClassData(j);
    }

    private void readClassData(Jar jar) {
        for (Map.Entry<String, byte[]> entry : jar) {
            classData.put(entry.getKey(), entry.getValue());
        }
    }

    private String formatClassName(String className) {
        return className.replace(".", "/") + ".class";
    }

    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        String fcn = formatClassName(className);

        if (classData.containsKey(fcn)) {
            byte[] cd = classData.get(fcn);
            
            return defineClass(className, cd, 0, cd.length);
        } else {
            throw new ClassNotFoundException(className);
        }
    }
}
